package cn.fatgod.learn.thymeleaf.standard;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class PropUtils {
    private final static String IS = "is";
    private final static String GET = "get";
    private final static String IMPORT_PATH = "importPath";
    private final static String S = "s";

    public static String getterName(Field field) {
        Class<?> type = field.getType();
        String name = field.getName();
        String getterName = Character.toUpperCase(name.charAt(0)) + name.substring(1);
        if (type.equals(boolean.class) || type.equals(Boolean.class)) {
            return IS + getterName;
        }
        if (name.equals(IMPORT_PATH)) {
            return GET + getterName + S;
        }
        return GET + getterName;
    }

    public static Object getValue(Object obj, Field field) {
        try {
            Class<?> clazz = obj.getClass();
            String getterName = getterName(field);
            Method getter = clazz.getDeclaredMethod(getterName);
            if (Modifier.isPrivate(getter.getModifiers())) {
                getter.setAccessible(true);
            }
            Object val = getter.invoke(obj);
            if (val != null) {
                return val;
            }
            if (Modifier.isPrivate(field.getModifiers())) {
                field.setAccessible(true);
            }
            return field.get(obj);
        } catch (Exception e) {
            throw new RuntimeException("反射获取值失败", e);
        }
    }
}
